package com.hsfw.pmauthzuul.filter;

import com.google.gson.Gson;
import com.hsfw.dbmodule.utils.BaseResponse;
import com.hsfw.dbmodule.utils.ResponseCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * Created by RAZR on 15:52 2019/3/22.
 */
@Component
public class AuthenticationEntryPoint implements org.springframework.security.web.AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        //验证为未登陆状态会进入此方法，认证错误
        Gson gson=new Gson();
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        String body = gson.toJson(BaseResponse.buildResponse().setCode(ResponseCode.UNAUTHORIZED).setMessage(authException.getMessage()).build());
        printWriter.write(body);
        printWriter.flush();
    }
}
